import*as e from"../../core/platform/platform.js";import*as t from"../../core/sdk/sdk.js";import*as n from"../../ui/legacy/legacy.js";import*as s from"../../core/common/common.js";import*as i from"../../core/host/host.js";import*as r from"../../core/i18n/i18n.js";import*as o from"../../core/root/root.js";import*as a from"../logs/logs.js";import*as c from"../../ui/legacy/components/utils/utils.js";import*as d from"../../ui/legacy/theme_support/theme_support.js";import*as u from"../bindings/bindings.js";import*as l from"../har/har.js";import*as h from"../workspace/workspace.js";self.injectedExtensionAPI=function(t,n,s,i,r,o,a){const c=new Set(i),d=window.chrome||{};if(Object.getOwnPropertyDescriptor(d,"devtools"))return;let u=!1,l=!1;function h(e,t){this._type=e,this._listeners=[],this._customDispatch=t}function p(){this.onRequestFinished=new S("network-request-finished",(function(e){const t=e.arguments[1];t.__proto__=new L(e.arguments[0]),this._fire(t)})),y(this,"network","onFinished","onRequestFinished"),this.onNavigated=new S("inspected-url-changed")}function m(e){this._id=e}function g(){const e={elements:new q,sources:new k};function t(t){return e[t]}for(const n in e)Object.defineProperty(this,n,{get:t.bind(null,n),enumerable:!0});this.applyStyleSheet=function(e){Y.sendRequest({command:"applyStyleSheet",styleSheet:e})}}function f(e){this._id=e,e&&(this.onShown=new S("view-shown-"+e,(function(e){const t=e.arguments[0];"number"==typeof t?this._fire(window.parent.frames[t]):this._fire()})),this.onHidden=new S("view-hidden,"+e))}function b(e){f.call(this,null),this._hostPanelName=e,this.onSelectionChanged=new S("panel-objectSelected-"+e)}function w(){this._plugins=new Map}function R(){this._plugins=new Map}function E(e){return function(...t){const n={__proto__:e.prototype};e.apply(n,t),function(e,t){for(const n in t){if("_"===n.charAt(0))continue;let s=null;for(let e=t;e&&!s;e=e.__proto__)s=Object.getOwnPropertyDescriptor(e,n);s&&("function"==typeof s.value?e[n]=s.value.bind(t):"function"==typeof s.get?e.__defineGetter__(n,s.get.bind(t)):Object.defineProperty(e,n,s))}}(this,n)}}function y(e,t,n,s){let i=!1;e.__defineGetter__(n,(function(){return i||(console.warn(t+"."+n+" is deprecated. Use "+t+"."+s+" instead"),i=!0),e[s]}))}function x(e){const t=e[e.length-1];return"function"==typeof t?t:void 0}h.prototype={addListener:function(e){if("function"!=typeof e)throw"addListener: callback is not a function";0===this._listeners.length&&Y.sendRequest({command:"subscribe",type:this._type}),this._listeners.push(e),Y.registerHandler("notify-"+this._type,this._dispatch.bind(this))},removeListener:function(e){const t=this._listeners;for(let n=0;n<t.length;++n)if(t[n]===e){t.splice(n,1);break}0===this._listeners.length&&Y.sendRequest({command:"unsubscribe",type:this._type})},_fire:function(...e){const t=this._listeners.slice();for(let e=0;e<t.length;++e)t[e].apply(null,Array.from(arguments))},_dispatch:function(e){this._customDispatch?this._customDispatch.call(this,e):this._fire.apply(this,e.arguments)}},p.prototype={getHAR:function(e){Y.sendRequest({command:"getHAR"},e&&function(t){const n=t,s=n&&n.entries||[];for(let e=0;e<s.length;++e)s[e].__proto__=new L(s[e]._requestId),delete s[e]._requestId;e&&e(n)})},addRequestHeaders:function(e){Y.sendRequest({command:"addRequestHeaders",headers:e,extensionId:window.location.hostname})}},m.prototype={getContent:function(e){Y.sendRequest({command:"getRequestContent",id:this._id},e&&function(t){const{content:n,encoding:s}=t;e&&e(n,s)})}},g.prototype={create:function(e,t,n,s){const i="extension-panel-"+Y.nextObjectId();Y.sendRequest({command:"createPanel",id:i,title:e,page:n},s&&(()=>s.call(this,new P(i))))},setOpenResourceHandler:function(e){const t=Y.hasHandler("open-resource");e?Y.registerHandler("open-resource",(function(t){u=!0;try{const{resource:n,lineNumber:s}=t;F(n)&&e.call(null,new C(n),s)}finally{u=!1}})):Y.unregisterHandler("open-resource"),t===!e&&Y.sendRequest({command:"setOpenResourceHandler",handlerPresent:Boolean(e)})},setThemeChangeHandler:function(e){const t=Y.hasHandler("host-theme-change");e?Y.registerHandler("host-theme-change",(function(t){const{themeName:n}=t;d.devtools.panels.themeName=n,e.call(null,n)})):Y.unregisterHandler("host-theme-change"),t===!e&&Y.sendRequest({command:"setThemeChangeHandler",handlerPresent:Boolean(e)})},openResource:function(e,t,n,s){const i=x(arguments),r="number"==typeof n?n:0;Y.sendRequest({command:"openResource",url:e,lineNumber:t,columnNumber:r},i)},get SearchAction(){return{CancelSearch:"cancelSearch",PerformSearch:"performSearch",NextSearchResult:"nextSearchResult",PreviousSearchResult:"previousSearchResult"}}},b.prototype={createSidebarPane:function(e,t){const n="extension-sidebar-"+Y.nextObjectId();Y.sendRequest({command:"createSidebarPane",panel:this._hostPanelName,id:n,title:e},t&&function(){t&&t(new O(n))})},__proto__:f.prototype},w.prototype={registerRecorderExtensionPlugin:async function(e,t,n){if(this._plugins.has(e))throw new Error(`Tried to register plugin '${t}' twice`);const s=new MessageChannel,i=s.port1;this._plugins.set(e,i),i.onmessage=({data:t})=>{const{requestId:n}=t;(async function(t){switch(t.method){case"stringify":return e.stringify(t.parameters.recording);case"stringifyStep":return e.stringifyStep(t.parameters.step);case"replay":try{return u=!0,l=!0,e.replay(t.parameters.recording)}finally{u=!1,l=!1}default:throw new Error(`'${t.method}' is not recognized`)}})(t).then((e=>i.postMessage({requestId:n,result:e}))).catch((e=>i.postMessage({requestId:n,error:{message:e.message}})))};const r=[];"stringify"in e&&"stringifyStep"in e&&r.push("export"),"replay"in e&&r.push("replay"),await new Promise((e=>{Y.sendRequest({command:"registerRecorderExtensionPlugin",pluginName:t,mediaType:n,capabilities:r,port:s.port2},(()=>e()),[s.port2])}))},unregisterRecorderExtensionPlugin:async function(e){const t=this._plugins.get(e);if(!t)throw new Error("Tried to unregister a plugin that was not previously registered");this._plugins.delete(e),t.postMessage({event:"unregisteredRecorderExtensionPlugin"}),t.close()},createView:async function(e,t){const n="recorder-extension-view-"+Y.nextObjectId();return await new Promise((s=>{Y.sendRequest({command:"createRecorderView",id:n,title:e,pagePath:t},s)})),new A(n)}},R.prototype={registerLanguageExtensionPlugin:async function(e,t,n){if(this._plugins.has(e))throw new Error(`Tried to register plugin '${t}' twice`);const s=new MessageChannel,i=s.port1;this._plugins.set(e,i),i.onmessage=({data:t})=>{const{requestId:n}=t;console.time(`${n}: ${t.method}`),function(t){switch(t.method){case"addRawModule":return e.addRawModule(t.parameters.rawModuleId,t.parameters.symbolsURL,t.parameters.rawModule);case"removeRawModule":return e.removeRawModule(t.parameters.rawModuleId);case"sourceLocationToRawLocation":return e.sourceLocationToRawLocation(t.parameters.sourceLocation);case"rawLocationToSourceLocation":return e.rawLocationToSourceLocation(t.parameters.rawLocation);case"getScopeInfo":return e.getScopeInfo(t.parameters.type);case"listVariablesInScope":return e.listVariablesInScope(t.parameters.rawLocation);case"getFunctionInfo":return e.getFunctionInfo(t.parameters.rawLocation);case"getInlinedFunctionRanges":return e.getInlinedFunctionRanges(t.parameters.rawLocation);case"getInlinedCalleesRanges":return e.getInlinedCalleesRanges(t.parameters.rawLocation);case"getMappedLines":return"getMappedLines"in e?e.getMappedLines(t.parameters.rawModuleId,t.parameters.sourceFileURL):Promise.resolve(void 0);case"formatValue":return"evaluate"in e&&e.evaluate?e.evaluate(t.parameters.expression,t.parameters.context,t.parameters.stopId):Promise.resolve(void 0);case"getProperties":if("getProperties"in e&&e.getProperties)return e.getProperties(t.parameters.objectId);if(!("evaluate"in e)||!e.evaluate)return Promise.resolve(void 0);break;case"releaseObject":if("releaseObject"in e&&e.releaseObject)return e.releaseObject(t.parameters.objectId)}throw new Error(`Unknown language plugin method ${t.method}`)}(t).then((e=>i.postMessage({requestId:n,result:e}))).catch((e=>i.postMessage({requestId:n,error:{message:e.message}}))).finally((()=>console.timeEnd(`${n}: ${t.method}`)))},await new Promise((e=>{Y.sendRequest({command:"registerLanguageExtensionPlugin",pluginName:t,port:s.port2,supportedScriptTypes:n},(()=>e()),[s.port2])}))},unregisterLanguageExtensionPlugin:async function(e){const t=this._plugins.get(e);if(!t)throw new Error("Tried to unregister a plugin that was not previously registered");this._plugins.delete(e),t.postMessage({event:"unregisteredLanguageExtensionPlugin"}),t.close()},getWasmLinearMemory:async function(e,t,n){const s=await new Promise((s=>Y.sendRequest({command:"getWasmLinearMemory",offset:e,length:t,stopId:n},s)));return Array.isArray(s)?new Uint8Array(s).buffer:new ArrayBuffer(0)},getWasmLocal:async function(e,t){return new Promise((n=>Y.sendRequest({command:"getWasmLocal",local:e,stopId:t},n)))},getWasmGlobal:async function(e,t){return new Promise((n=>Y.sendRequest({command:"getWasmGlobal",global:e,stopId:t},n)))},getWasmOp:async function(e,t){return new Promise((n=>Y.sendRequest({command:"getWasmOp",op:e,stopId:t},n)))}};const v=E(R),_=E(w),I=E(N),S=E(h),P=E(M),A=E(j),O=E(D),T=E(b),L=E(m),C=E(G),H=E(B);class q extends T{constructor(){super("elements")}}class k extends T{constructor(){super("sources")}}function M(e){f.call(this,e),this.onSearch=new S("panel-search-"+e)}function j(e){f.call(this,e)}function D(e){f.call(this,e)}function N(e){this._id=e,this.onClicked=new S("button-clicked-"+e)}function W(){}function B(e){this._id=e}function U(e){this.onRecordingStarted=new S("trace-recording-started-"+e,(function(e){const t=e.arguments[0];this._fire(new H(t))})),this.onRecordingStopped=new S("trace-recording-stopped-"+e)}function F(e){try{return t.allowFileAccess||"file:"!==new URL(e.url).protocol}catch(e){return!1}}function V(){this.onResourceAdded=new S("resource-added",(function(e){const t=e.arguments[0];F(t)&&this._fire(new C(t))})),this.onResourceContentCommitted=new S("resource-content-committed",(function(e){const t=e.arguments[0];F(t)&&this._fire(new C(t),e.arguments[1])}))}function G(e){if(!F)throw new Error("Resource access not allowed");this._url=e.url,this._type=e.type}M.prototype={createStatusBarButton:function(e,t,n){const s="button-"+Y.nextObjectId();return Y.sendRequest({command:"createToolbarButton",panel:this._id,id:s,icon:e,tooltip:t,disabled:Boolean(n)}),new I(s)},show:function(){u&&Y.sendRequest({command:"showPanel",id:this._id})},__proto__:f.prototype},j.prototype={show:function(){u&&l&&Y.sendRequest({command:"showRecorderView",id:this._id})},__proto__:f.prototype},D.prototype={setHeight:function(e){Y.sendRequest({command:"setSidebarHeight",id:this._id,height:e})},setExpression:function(e,t,n,s){Y.sendRequest({command:"setSidebarContent",id:this._id,expression:e,rootTitle:t,evaluateOnPage:!0,evaluateOptions:"object"==typeof n?n:{}},x(arguments))},setObject:function(e,t,n){Y.sendRequest({command:"setSidebarContent",id:this._id,expression:e,rootTitle:t},n)},setPage:function(e){Y.sendRequest({command:"setSidebarPage",id:this._id,page:e})},__proto__:f.prototype},N.prototype={update:function(e,t,n){Y.sendRequest({command:"updateButton",id:this._id,icon:e,tooltip:t,disabled:Boolean(n)})}},W.prototype={addTraceProvider:function(e,t){const n="extension-trace-provider-"+Y.nextObjectId();return Y.sendRequest({command:"addTraceProvider",id:n,categoryName:e,categoryTooltip:t}),new U(n)}},B.prototype={complete:function(t,n){Y.sendRequest({command:"completeTra.eSession",id:this._id,url:t||e.DevToolsPath.EmptyUrlString,timeOffset:n||0})}},V.prototype={reload:function(e){let t=null;"object"==typeof e?t=e:"string"==typeof e&&(t={userAgent:e},console.warn("Passing userAgent as string parameter to inspectedWindow.reload() is deprecated. Use inspectedWindow.reload({ userAgent: value}) instead.")),Y.sendRequest({command:"Reload",options:t})},eval:function(e,t){const n=x(arguments);function s(e){const{isError:t,isException:s,value:i}=e;t||s?n&&n(void 0,e):n&&n(i)}return Y.sendRequest({command:"evaluateOnInspectedPage",expression:e,evaluateOptions:"object"==typeof t?t:void 0},n&&s),null},getResources:function(e){function t(e){return new C(e)}Y.sendRequest({command:"getPageResources"},e&&function(n){e&&e(n.map(t).filter(F))})}},G.prototype={get url(){return this._url},get type(){return this._type},getContent:function(e){Y.sendRequest({command:"getResourceContent",url:this._url},e&&function(t){const{content:n,encoding:s}=t;e&&e(n,s)})},setContent:function(e,t,n){Y.sendRequest({command:"setResourceContent",url:this._url,content:e,commit:t},n)}};let K=[],$=null;function z(){$=null,Y.sendRequest({command:"_forwardKeyboardEvent",entries:K}),K=[]}function X(e){this._callbacks={},this._handlers={},this._lastRequestId=0,this._lastObjectId=0,this.registerHandler("callback",this._onCallback.bind(this));const t=new MessageChannel;this._port=t.port1,this._port.addEventListener("message",this._onMessage.bind(this),!1),this._port.start(),e.postMessage("registerExtension","*",[t.port2])}document.addEventListener("keydown",(function(e){const t=document.activeElement;if(t){if(("INPUT"===t.nodeName||"TEXTAREA"===t.nodeName||t.isContentEditable)&&!(e.ctrlKey||e.altKey||e.metaKey))return}let n=0;e.shiftKey&&(n|=1),e.ctrlKey&&(n|=2),e.altKey&&(n|=4),e.metaKey&&(n|=8);const s=255&e.keyCode|n<<8;if(!c.has(s))return;e.preventDefault();const i={eventType:e.type,ctrlKey:e.ctrlKey,altKey:e.altKey,metaKey:e.metaKey,shiftKey:e.shiftKey,keyIdentifier:e.keyIdentifier,key:e.key,code:e.code,location:e.location,keyCode:e.keyCode};K.push(i),$||($=window.setTimeout(z,0))}),!1),X.prototype={sendRequest:function(e,t,n){"function"==typeof t&&(e.requestId=this._registerCallback(t)),this._port.postMessage(e,n)},hasHandler:function(e){return Boolean(this._handlers[e])},registerHandler:function(e,t){this._handlers[e]=t},unregisterHandler:function(e){delete this._handlers[e]},nextObjectId:function(){return o.toString()+"_"+ ++this._lastObjectId},_registerCallback:function(e){const t=++this._lastRequestId;return this._callbacks[t]=e,t},_onCallback:function(e){if(e.requestId in this._callbacks){const t=this._callbacks[e.requestId];delete this._callbacks[e.requestId],t(e.result)}},_onMessage:function(e){const t=e.data,n=this._handlers[t.command];n&&n.call(this,t)}};const Y=new X(a||window.parent),J=new function(){this.inspectedWindow=new V,this.panels=new g,this.network=new p,this.timeline=new W,this.languageServices=new v,this.recorder=new _,y(this,"webInspector","resources","network")};if(Object.defineProperty(d,"devtools",{value:{},enumerable:!0}),d.devtools.inspectedWindow={},Object.defineProperty(d.devtools.inspectedWindow,"tabId",{get:function(){return n}}),d.devtools.inspectedWindow.__proto__=J.inspectedWindow,d.devtools.network=J.network,d.devtools.panels=J.panels,d.devtools.panels.themeName=s,d.devtools.languageServices=J.languageServices,d.devtools.recorder=J.recorder,!1!==t.exposeExperimentalAPIs){d.experimental=d.experimental||{},d.experimental.devtools=d.experimental.devtools||{};const e=Object.getOwnPropertyNames(J);for(let t=0;t<e.length;++t){const n=Object.getOwnPropertyDescriptor(J,e[t]);n&&Object.defineProperty(d.experimental.devtools,e[t],n)}d.experimental.devtools.inspectedWindow=d.devtools.inspectedWindow}t.exposeWebInspectorNamespace&&(window.webInspector=J),r(Y,J)},self.buildExtensionAPIInjectedScript=function(e,t,n,s,i){const r=[e,t||null,n,s].map((e=>JSON.stringify(e))).join(",");return i||(i=()=>{}),"(function(injectedScriptId){ ("+self.injectedExtensionAPI.toString()+")("+r+","+i+", injectedScriptId);})"};var p=Object.freeze({__proto__:null});class m extends n.Widget.Widget{server;id;iframe;frameIndex;constructor(e,t,n,s){super(),this.setHideOnDetach(),this.element.className="vbox flex-auto",this.element.tabIndex=-1,this.server=e,this.id=t,this.iframe=document.createElement("iframe"),this.iframe.addEventListener("load",this.onLoad.bind(this),!1),this.iframe.src=n,this.iframe.className=s,this.setDefaultFocusedElement(this.element),this.element.appendChild(this.iframe)}wasShown(){super.wasShown(),"number"==typeof this.frameIndex&&this.server.notifyViewShown(this.id,this.frameIndex)}willHide(){"number"==typeof this.frameIndex&&this.server.notifyViewHidden(this.id)}onLoad(){const e=window.frames;this.frameIndex=Array.prototype.indexOf.call(e,this.iframe.contentWindow),this.isShowing()&&this.server.notifyViewShown(this.id,this.frameIndex)}}class g extends n.Widget.VBox{server;id;constructor(e,t){super(),this.server=e,this.id=t}wasShown(){this.server.notifyViewShown(this.id)}willHide(){this.server.notifyViewHidden(this.id)}}var f=Object.freeze({__proto__:null,ExtensionView:m,ExtensionNotifierView:g});class b extends n.Panel.Panel{server;id;panelToolbar;searchableViewInternal;constructor(e,t,s,i){super(t),this.server=e,this.id=s,this.setHideOnDetach(),this.panelToolbar=new n.Toolbar.Toolbar("hidden",this.element),this.searchableViewInternal=new n.SearchableView.SearchableView(this,null),this.searchableViewInternal.show(this.element);new m(e,this.id,i,"extension").show(this.searchableViewInternal.element)}addToolbarItem(e){this.panelToolbar.element.classList.remove("hidden"),this.panelToolbar.appendToolbarItem(e)}onSearchCanceled(){this.server.notifySearchAction(this.id,"cancelSearch"),this.searchableViewInternal.updateSearchMatchesCount(0)}searchableView(){return this.searchableViewInternal}performSearch(e,t,n){const s=e.query;this.server.notifySearchAction(this.id,"performSearch",s)}jumpToNextSearchResult(){this.server.notifySearchAction(this.id,"nextSearchResult")}jumpToPreviousSearchResult(){this.server.notifySearchAction(this.id,"previousSearchResult")}supportsCaseSensitiveSearch(){return!1}supportsRegexSearch(){return!1}}class w{id;toolbarButtonInternal;constructor(e,t,s,i,r){this.id=t,this.toolbarButtonInternal=new n.Toolbar.ToolbarButton("",""),this.toolbarButtonInternal.addEventListener(n.Toolbar.ToolbarButton.Events.Click,e.notifyButtonClicked.bind(e,this.id)),this.update(s,i,r)}update(e,t,n){"string"==typeof e&&this.toolbarButtonInternal.setBackgroundImage(e),"string"==typeof t&&this.toolbarButtonInternal.setTitle(t),"boolean"==typeof n&&this.toolbarButtonInternal.setEnabled(!n)}toolbarButton(){return this.toolbarButtonInternal}}class R extends n.View.SimpleView{panelNameInternal;server;idInternal;extensionView;objectPropertiesView;constructor(e,t,n,s){super(n),this.element.classList.add("fill"),this.panelNameInternal=t,this.server=e,this.idInternal=s}id(){return this.idInternal}panelName(){return this.panelNameInternal}setObject(e,n,s){this.createObjectPropertiesView(),this.setObjectInternal(t.RemoteObject.RemoteObject.fromLocalObject(e),n,s)}setExpression(e,t,n,s,i){this.createObjectPropertiesView(),this.server.evaluate(e,!0,!1,n,s,this.onEvaluate.bind(this,t,i))}setPage(e){this.objectPropertiesView&&(this.objectPropertiesView.detach(),delete this.objectPropertiesView),this.extensionView&&this.extensionView.detach(!0),this.extensionView=new m(this.server,this.idInternal,e,"extension fill"),this.extensionView.show(this.element),this.element.style.height||this.setHeight("150px")}setHeight(e){this.element.style.height=e}onEvaluate(e,t,n,s,i){n?t(n.toString()):s?this.setObjectInternal(s,e,t):t()}createObjectPropertiesView(){this.objectPropertiesView||(this.extensionView&&(this.extensionView.detach(!0),delete this.extensionView),this.objectPropertiesView=new g(this.server,this.idInternal),this.objectPropertiesView.show(this.element))}setObjectInternal(e,t,s){const i=this.objectPropertiesView;i?(i.element.removeChildren(),n.UIUtils.Renderer.render(e,{title:t,editable:!1}).then((e=>{if(!e)return void s();const t=e.tree&&e.tree.firstChild();t&&t.expand(),i.element.appendChild(e.node),s()}))):s("operation cancelled")}}var E=Object.freeze({__proto__:null,ExtensionPanel:b,ExtensionButton:w,ExtensionSidebarPane:R});function y(e){switch(e){case"http":return"80";case"https":return"443";case"ftp":return"25"}}class x{pattern;static parse(e){if("<all_urls>"===e)return new x({matchesAll:!0});const t=function(e){const t=e.indexOf("://");if(t<0)return;const n=e.substr(0,t).toLowerCase();return["*","http","https","ftp","chrome","chrome-extension"].includes(n)?{scheme:n,hostPattern:e.substr(t+"://".length)}:void 0}(e);if(!t)return;const{scheme:n,hostPattern:s}=t,i=function(e,t){const n=e.indexOf("/");if(n>=0){const t=e.substr(n);if("/*"!==t&&"/"!==t)return;e=e.substr(0,n)}if(e.endsWith(":*")&&(e=e.substr(0,e.length-":*".length)),e.endsWith(":"))return;let s;try{s=new URL(e.startsWith("*.")?`http://${e.substr("*.".length)}`:`http://${e}`)}catch{return}if("/"!==s.pathname)return;if(s.hostname.endsWith(".")&&(s.hostname=s.hostname.substr(0,s.hostname.length-1)),"%2A"!==s.hostname&&s.hostname.includes("%2A"))return;const i=y("http");if(!i)return;const r=e.endsWith(`:${i}`)?i:""===s.port?"*":s.port;if("*"!==r&&!["http","https","ftp"].includes(t))return;return{host:"%2A"!==s.hostname?e.startsWith("*.")?`*.${s.hostname}`:s.hostname:"*",port:r}}(s,n);if(!i)return;const{host:r,port:o}=i;return new x({scheme:n,host:r,port:o,matchesAll:!1})}constructor(e){this.pattern=e}get scheme(){return this.pattern.matchesAll?"*":this.pattern.scheme}get host(){return this.pattern.matchesAll?"*":this.pattern.host}get port(){return this.pattern.matchesAll?"*":this.pattern.port}matchesAllUrls(){return this.pattern.matchesAll}matchesUrl(e){let t;try{t=new URL(e)}catch{return!1}if(this.matchesAllUrls())return!0;const n=t.protocol.substr(0,t.protocol.length-1),s=t.port||y(n);return this.matchesScheme(n)&&this.matchesHost(t.hostname)&&(!s||this.matchesPort(s))}matchesScheme(e){return!!this.pattern.matchesAll||("*"===this.pattern.scheme?"http"===e||"https"===e:this.pattern.scheme===e)}matchesHost(e){if(this.pattern.matchesAll)return!0;if("*"===this.pattern.host)return!0;let t=new URL(`http://${e}`).hostname;return t.endsWith(".")&&(t=t.substr(0,t.length-1)),this.pattern.host.startsWith("*.")?t===this.pattern.host.substr(2)||t.endsWith(this.pattern.host.substr(1)):this.pattern.host===t}matchesPort(e){return!!this.pattern.matchesAll||("*"===this.pattern.port||this.pattern.port===e)}}var v=Object.freeze({__proto__:null,HostUrlPattern:x});class _{port;nextRequestId=0;pendingRequests;constructor(e){this.port=e,this.port.onmessage=this.onResponse.bind(this),this.pendingRequests=new Map}sendRequest(e,t){return new Promise(((n,s)=>{const i=this.nextRequestId++;this.pendingRequests.set(i,{resolve:n,reject:s}),this.port.postMessage({requestId:i,method:e,parameters:t})}))}disconnect(){for(const{reject:e}of this.pendingRequests.values())e(new Error("Extension endpoint disconnected"));this.pendingRequests.clear(),this.port.close()}onResponse({data:e}){if("event"in e)return void this.handleEvent(e);const{requestId:t,result:n,error:s}=e,i=this.pendingRequests.get(t);i?(this.pendingRequests.delete(t),s?i.reject(new Error(s.message)):i.resolve(n)):console.error(`No pending request ${t}`)}handleEvent(e){throw new Error("handleEvent is not implemented")}}class I extends _{plugin;constructor(e,t){super(t),this.plugin=e}handleEvent({event:e}){switch(e){case"unregisteredLanguageExtensionPlugin":{this.disconnect();const{pluginManager:e}=u.DebuggerWorkspaceBinding.DebuggerWorkspaceBinding.instance();e&&e.removePlugin(this.plugin);break}}}}class S{supportedScriptTypes;endpoint;name;constructor(e,t,n){this.name=e,this.supportedScriptTypes=t,this.endpoint=new I(this,n)}handleScript(e){const t=e.scriptLanguage();return null!==t&&null!==e.debugSymbols&&t===this.supportedScriptTypes.language&&this.supportedScriptTypes.symbol_types.includes(e.debugSymbols.type)}addRawModule(e,t,n){return this.endpoint.sendRequest("addRawModule",{rawModuleId:e,symbolsURL:t,rawModule:n})}removeRawModule(e){return this.endpoint.sendRequest("removeRawModule",{rawModuleId:e})}sourceLocationToRawLocation(e){return this.endpoint.sendRequest("sourceLocationToRawLocation",{sourceLocation:e})}rawLocationToSourceLocation(e){return this.endpoint.sendRequest("rawLocationToSourceLocation",{rawLocation:e})}getScopeInfo(e){return this.endpoint.sendRequest("getScopeInfo",{type:e})}listVariablesInScope(e){return this.endpoint.sendRequest("listVariablesInScope",{rawLocation:e})}getFunctionInfo(e){return this.endpoint.sendRequest("getFunctionInfo",{rawLocation:e})}getInlinedFunctionRanges(e){return this.endpoint.sendRequest("getInlinedFunctionRanges",{rawLocation:e})}getInlinedCalleesRanges(e){return this.endpoint.sendRequest("getInlinedCalleesRanges",{rawLocation:e})}async getMappedLines(e,t){return this.endpoint.sendRequest("getMappedLines",{rawModuleId:e,sourceFileURL:t})}async evaluate(e,t,n){return this.endpoint.sendRequest("formatValue",{expression:e,context:t,stopId:n})}getProperties(e){return this.endpoint.sendRequest("getProperties",{objectId:e})}releaseObject(e){return this.endpoint.sendRequest("releaseObject",{objectId:e})}}let P=null;class A extends s.ObjectWrapper.ObjectWrapper{#e=new Set;#t=new Map;static instance(){return P||(P=new A),P}addPlugin(e){this.#e.add(e),this.dispatchEventToListeners(O.PluginAdded,e)}removePlugin(e){this.#e.delete(e),this.dispatchEventToListeners(O.PluginRemoved,e)}plugins(){return Array.from(this.#e.values())}registerView(e){this.#t.set(e.id,e),this.dispatchEventToListeners(O.ViewRegistered,e)}views(){return Array.from(this.#t.values())}getViewDescriptor(e){return this.#t.get(e)}showView(e){const t=this.#t.get(e);if(!t)throw new Error(`View with id ${e} is not found.`);this.dispatchEventToListeners(O.ShowViewRequested,t)}}var O;!function(e){e.PluginAdded="pluginAdded",e.PluginRemoved="pluginRemoved",e.ViewRegistered="viewRegistered",e.ShowViewRequested="showViewRequested"}(O||(O={}));var T=Object.freeze({__proto__:null,RecorderPluginManager:A,get Events(){return O}});class L extends _{name;mediaType;capabilities;constructor(e,t,n,s){super(t),this.name=e,this.mediaType=s,this.capabilities=n}getName(){return this.name}getCapabilities(){return this.capabilities}getMediaType(){return this.mediaType}handleEvent({event:e}){if("unregisteredRecorderExtensionPlugin"!==e)throw new Error(`Unrecognized Recorder extension endpoint event: ${e}`);this.disconnect(),A.instance().removePlugin(this)}stringify(e){return this.sendRequest("stringify",{recording:e})}stringifyStep(e){return this.sendRequest("stringifyStep",{step:e})}replay(e){return this.sendRequest("replay",{recording:e})}}var C=Object.freeze({__proto__:null,RecorderExtensionEndpoint:L});const H=new WeakMap,q=[].map((e=>new URL(e).origin));let k;class M{runtimeAllowedHosts;runtimeBlockedHosts;static create(e){const t=[],n=[];if(e){for(const n of e.runtimeAllowedHosts){const e=x.parse(n);if(!e)return null;t.push(e)}for(const t of e.runtimeBlockedHosts){const e=x.parse(t);if(!e)return null;n.push(e)}}return new M(t,n)}constructor(e,t){this.runtimeAllowedHosts=e,this.runtimeBlockedHosts=t}isAllowedOnURL(e){return e?!(this.runtimeBlockedHosts.some((t=>t.matchesUrl(e)))&&!this.runtimeAllowedHosts.some((t=>t.matchesUrl(e)))):0===this.runtimeBlockedHosts.length}}class j{name;hostsPolicy;allowFileAccess;constructor(e,t,n){this.name=e,this.hostsPolicy=t,this.allowFileAccess=n}isAllowedOnTarget(e){if(e||(e=t.TargetManager.TargetManager.instance().primaryPageTarget()?.inspectedURL()),!e)return!1;if(!D.canInspectURL(e))return!1;if(!this.hostsPolicy.isAllowedOnURL(e))return!1;if(!this.allowFileAccess){let t;try{t=new URL(e)}catch(e){return!1}return"file:"!==t.protocol}return!0}}class D extends s.ObjectWrapper.ObjectWrapper{clientObjects;handlers;subscribers;subscriptionStartHandlers;subscriptionStopHandlers;extraHeaders;requests;requestIds;lastRequestId;registeredExtensions;status;sidebarPanesInternal;extensionsEnabled;inspectedTabId;extensionAPITestHook;themeChangeHandlers=new Map;#n=[];constructor(){super(),this.clientObjects=new Map,this.handlers=new Map,this.subscribers=new Map,this.subscriptionStartHandlers=new Map,this.subscriptionStopHandlers=new Map,this.extraHeaders=new Map,this.requests=new Map,this.requestIds=new Map,this.lastRequestId=0,this.registeredExtensions=new Map,this.status=new B,this.sidebarPanesInternal=[],this.extensionsEnabled=!0,this.registerHandler("addRequestHeaders",this.onAddRequestHeaders.bind(this)),this.registerHandler("applyStyleSheet",this.onApplyStyleSheet.bind(this)),this.registerHandler("createPanel",this.onCreatePanel.bind(this)),this.registerHandler("createSidebarPane",this.onCreateSidebarPane.bind(this)),this.registerHandler("createToolbarButton",this.onCreateToolbarButton.bind(this)),this.registerHandler("evaluateOnInspectedPage",this.onEvaluateOnInspectedPage.bind(this)),this.registerHandler("_forwardKeyboardEvent",this.onForwardKeyboardEvent.bind(this)),this.registerHandler("getHAR",this.onGetHAR.bind(this)),this.registerHandler("getPageResources",this.onGetPageResources.bind(this)),this.registerHandler("getRequestContent",this.onGetRequestContent.bind(this)),this.registerHandler("getResourceContent",this.onGetResourceContent.bind(this)),this.registerHandler("Reload",this.onReload.bind(this)),this.registerHandler("setOpenResourceHandler",this.onSetOpenResourceHandler.bind(this)),this.registerHandler("setThemeChangeHandler",this.onSetThemeChangeHandler.bind(this)),this.registerHandler("setResourceContent",this.onSetResourceContent.bind(this)),this.registerHandler("setSidebarHeight",this.onSetSidebarHeight.bind(this)),this.registerHandler("setSidebarContent",this.onSetSidebarContent.bind(this)),this.registerHandler("setSidebarPage",this.onSetSidebarPage.bind(this)),this.registerHandler("showPanel",this.onShowPanel.bind(this)),this.registerHandler("subscribe",this.onSubscribe.bind(this)),this.registerHandler("openResource",this.onOpenResource.bind(this)),this.registerHandler("unsubscribe",this.onUnsubscribe.bind(this)),this.registerHandler("updateButton",this.onUpdateButton.bind(this)),this.registerHandler("registerLanguageExtensionPlugin",this.registerLanguageExtensionEndpoint.bind(this)),this.registerHandler("getWasmLinearMemory",this.onGetWasmLinearMemory.bind(this)),this.registerHandler("getWasmGlobal",this.onGetWasmGlobal.bind(this)),this.registerHandler("getWasmLocal",this.onGetWasmLocal.bind(this)),this.registerHandler("getWasmOp",this.onGetWasmOp.bind(this)),this.registerHandler("registerRecorderExtensionPlugin",this.registerRecorderExtensionEndpoint.bind(this)),this.registerHandler("createRecorderView",this.onCreateRecorderView.bind(this)),this.registerHandler("showRecorderView",this.onShowRecorderView.bind(this)),window.addEventListener("message",this.onWindowMessage,!1);const e=window.DevToolsAPI&&window.DevToolsAPI.getInspectedTabId&&window.DevToolsAPI.getInspectedTabId();e&&this.setInspectedTabId({data:e}),i.InspectorFrontendHost.InspectorFrontendHostInstance.events.addEventListener(i.InspectorFrontendHostAPI.Events.SetInspectedTabId,this.setInspectedTabId,this),this.initExtensions(),d.ThemeSupport.instance().addEventListener(d.ThemeChangeEvent.eventName,this.#s)}dispose(){d.ThemeSupport.instance().removeEventListener(d.ThemeChangeEvent.eventName,this.#s),t.TargetManager.TargetManager.instance().removeEventListener(t.TargetManager.Events.InspectedURLChanged,this.inspectedURLChanged,this),i.InspectorFrontendHost.InspectorFrontendHostInstance.events.removeEventListener(i.InspectorFrontendHostAPI.Events.SetInspectedTabId,this.setInspectedTabId,this),window.removeEventListener("message",this.onWindowMessage,!1)}#s=()=>{const e=d.ThemeSupport.instance().themeName();for(const t of this.themeChangeHandlers.values())t.postMessage({command:"host-theme-change",themeName:e})};static instance(e={forceNew:null}){const{forceNew:t}=e;return k&&!t||(k?.dispose(),k=new D),k}initializeExtensions(){null!==this.inspectedTabId&&i.InspectorFrontendHost.InspectorFrontendHostInstance.setAddExtensionCallback(this.addExtension.bind(this))}hasExtensions(){return Boolean(this.registeredExtensions.size)}notifySearchAction(e,t,n){this.postNotification("panel-search-"+e,t,n)}notifyViewShown(e,t){this.postNotification("view-shown-"+e,t)}notifyViewHidden(e){this.postNotification("view-hidden,"+e)}notifyButtonClicked(e){this.postNotification("button-clicked-"+e)}registerLanguageExtensionEndpoint(e,t){if("registerLanguageExtensionPlugin"!==e.command)return this.status.E_BADARG("command","expected registerLanguageExtensionPlugin");const{pluginManager:n}=u.DebuggerWorkspaceBinding.DebuggerWorkspaceBinding.instance();if(!n)return this.status.E_FAILED("WebAssembly DWARF support needs to be enabled to use this extension");const{pluginName:s,port:i,supportedScriptTypes:{language:r,symbol_types:o}}=e,a=Array.isArray(o)&&o.every((e=>"string"==typeof e))?o:[],c=new S(s,{language:r,symbol_types:a},i);return n.addPlugin(c),this.status.OK()}async loadWasmValue(e,t){const{pluginManager:n}=u.DebuggerWorkspaceBinding.DebuggerWorkspaceBinding.instance();if(!n)return this.status.E_FAILED("WebAssembly DWARF support needs to be enabled to use this extension");const s=n.callFrameForStopId(t);if(!s)return this.status.E_BADARG("stopId","Unknown stop id");const i=await s.debuggerModel.agent.invoke_evaluateOnCallFrame({callFrameId:s.id,expression:e,silent:!0,returnByValue:!0,throwOnSideEffect:!0});return i.exceptionDetails||i.getError()?this.status.E_FAILED("Failed"):i.result.value}async onGetWasmLinearMemory(e){return"getWasmLinearMemory"!==e.command?this.status.E_BADARG("command","expected getWasmLinearMemory"):await this.loadWasmValue(`[].slice.call(new Uint8Array(memories[0].buffer, ${Number(e.offset)}, ${Number(e.length)}))`,e.stopId)}async onGetWasmGlobal(e){return"getWasmGlobal"!==e.command?this.status.E_BADARG("command","expected getWasmGlobal"):this.loadWasmValue(`globals[${Number(e.global)}]`,e.stopId)}async onGetWasmLocal(e){return"getWasmLocal"!==e.command?this.status.E_BADARG("command","expected getWasmLocal"):this.loadWasmValue(`locals[${Number(e.local)}]`,e.stopId)}async onGetWasmOp(e){return"getWasmOp"!==e.command?this.status.E_BADARG("command","expected getWasmOp"):this.loadWasmValue(`stack[${Number(e.op)}]`,e.stopId)}registerRecorderExtensionEndpoint(e,t){if("registerRecorderExtensionPlugin"!==e.command)return this.status.E_BADARG("command","expected registerRecorderExtensionPlugin");const{pluginName:n,mediaType:s,port:i,capabilities:r}=e;return A.instance().addPlugin(new L(n,i,r,s)),this.status.OK()}onShowRecorderView(e){if("showRecorderView"!==e.command)return this.status.E_BADARG("command","expected showRecorderView");A.instance().showView(e.id)}onCreateRecorderView(e,t){if("createRecorderView"!==e.command)return this.status.E_BADARG("command","expected createRecorderView");const n=e.id;if(this.clientObjects.has(n))return this.status.E_EXISTS(n);const s=D.expandResourcePath(this.getExtensionOrigin(t),e.pagePath);if(void 0===s)return this.status.E_BADARG("pagePath","Resources paths cannot point to non-extension resources");return A.instance().registerView({id:n,pagePath:s,title:e.title,onShown:()=>this.notifyViewShown(n),onHidden:()=>this.notifyViewHidden(n)}),this.status.OK()}inspectedURLChanged(e){if(!D.canInspectURL(e.data.inspectedURL()))return void this.disableExtensions();if(e.data!==t.TargetManager.TargetManager.instance().primaryPageTarget())return;this.requests=new Map;const n=e.data.inspectedURL();this.postNotification("inspected-url-changed",n),this.#n.forEach((e=>this.addExtension(e))),this.#n.splice(0)}hasSubscribers(e){return this.subscribers.has(e)}postNotification(e,...t){if(!this.extensionsEnabled)return;const n=this.subscribers.get(e);if(!n)return;const s={command:"notify-"+e,arguments:Array.prototype.slice.call(arguments,1)};for(const e of n)this.extensionEnabled(e)&&e.postMessage(s)}onSubscribe(e,t){if("subscribe"!==e.command)return this.status.E_BADARG("command","expected subscribe");const n=this.subscribers.get(e.type);if(n)n.add(t);else{this.subscribers.set(e.type,new Set([t]));const n=this.subscriptionStartHandlers.get(e.type);n&&n()}}onUnsubscribe(e,t){if("unsubscribe"!==e.command)return this.status.E_BADARG("command","expected unsubscribe");const n=this.subscribers.get(e.type);if(n&&(n.delete(t),!n.size)){this.subscribers.delete(e.type);const t=this.subscriptionStopHandlers.get(e.type);t&&t()}}onAddRequestHeaders(e){if("addRequestHeaders"!==e.command)return this.status.E_BADARG("command","expected addRequestHeaders");const n=e.extensionId;if("string"!=typeof n)return this.status.E_BADARGTYPE("extensionId",typeof n,"string");let s=this.extraHeaders.get(n);s||(s=new Map,this.extraHeaders.set(n,s));for(const t in e.headers)s.set(t,e.headers[t]);const i={};for(const e of this.extraHeaders.values())for(const[t,n]of e)"__proto__"!==t&&"string"==typeof n&&(i[t]=n);t.NetworkManager.MultitargetNetworkManager.instance().setExtraHTTPHeaders(i)}onApplyStyleSheet(e){if("applyStyleSheet"!==e.command)return this.status.E_BADARG("command","expected applyStyleSheet");if(!o.Runtime.experiments.isEnabled("applyCustomStylesheet"))return;const t=document.createElement("style");t.textContent=e.styleSheet,document.head.appendChild(t),d.ThemeSupport.instance().addCustomStylesheet(e.styleSheet);for(let e=document.body;e;e=e.traverseNextNode(document.body))e instanceof ShadowRoot&&d.ThemeSupport.instance().injectCustomStyleSheets(e)}getExtensionOrigin(e){const t=H.get(e);if(!t)throw new Error("Received a message from an unregistered extension");return t}onCreatePanel(e,t){if("createPanel"!==e.command)return this.status.E_BADARG("command","expected createPanel");const s=e.id;if(this.clientObjects.has(s)||n.InspectorView.InspectorView.instance().hasPanel(s))return this.status.E_EXISTS(s);const i=D.expandResourcePath(this.getExtensionOrigin(t),e.page);if(void 0===i)return this.status.E_BADARG("page","Resources paths cannot point to non-extension resources");let o=this.getExtensionOrigin(t)+e.title;o=o.replace(/\s/g,"");const a=new W(o,r.i18n.lockedString(e.title),new b(this,o,s,i));return this.clientObjects.set(s,a),n.InspectorView.InspectorView.instance().addPanel(a),this.status.OK()}onShowPanel(e){if("showPanel"!==e.command)return this.status.E_BADARG("command","expected showPanel");let t=e.id;const s=this.clientObjects.get(e.id);s&&s instanceof W&&(t=s.viewId()),n.InspectorView.InspectorView.instance().showPanel(t)}onCreateToolbarButton(e,t){if("createToolbarButton"!==e.command)return this.status.E_BADARG("command","expected createToolbarButton");const n=this.clientObjects.get(e.panel);if(!(n&&n instanceof W))return this.status.E_NOTFOUND(e.panel);const s=D.expandResourcePath(this.getExtensionOrigin(t),e.icon);if(void 0===s)return this.status.E_BADARG("icon","Resources paths cannot point to non-extension resources");const i=new w(this,e.id,s,e.tooltip,e.disabled);return this.clientObjects.set(e.id,i),n.widget().then((function(e){e.addToolbarItem(i.toolbarButton())})),this.status.OK()}onUpdateButton(e,t){if("updateButton"!==e.command)return this.status.E_BADARG("command","expected updateButton");const n=this.clientObjects.get(e.id);if(!(n&&n instanceof w))return this.status.E_NOTFOUND(e.id);const s=e.icon&&D.expandResourcePath(this.getExtensionOrigin(t),e.icon);return e.icon&&void 0===s?this.status.E_BADARG("icon","Resources paths cannot point to non-extension resources"):(n.update(s,e.tooltip,e.disabled),this.status.OK())}onCreateSidebarPane(e){if("createSidebarPane"!==e.command)return this.status.E_BADARG("command","expected createSidebarPane");const t=e.id,n=new R(this,e.panel,r.i18n.lockedString(e.title),t);return this.sidebarPanesInternal.push(n),this.clientObjects.set(t,n),this.dispatchEventToListeners(N.SidebarPaneAdded,n),this.status.OK()}sidebarPanes(){return this.sidebarPanesInternal}onSetSidebarHeight(e){if("setSidebarHeight"!==e.command)return this.status.E_BADARG("command","expected setSidebarHeight");const t=this.clientObjects.get(e.id);return t&&t instanceof R?(t.setHeight(e.height),this.status.OK()):this.status.E_NOTFOUND(e.id)}onSetSidebarContent(e,t){if("setSidebarContent"!==e.command)return this.status.E_BADARG("command","expected setSidebarContent");const{requestId:n,id:s,rootTitle:i,expression:r,evaluateOptions:o,evaluateOnPage:a}=e,c=this.clientObjects.get(s);if(!(c&&c instanceof R))return this.status.E_NOTFOUND(e.id);function d(e){const s=e?this.status.E_FAILED(e):this.status.OK();this.dispatchCallback(n,t,s)}a?c.setExpression(r,i,o,this.getExtensionOrigin(t),d.bind(this)):c.setObject(e.expression,e.rootTitle,d.bind(this))}onSetSidebarPage(e,t){if("setSidebarPage"!==e.command)return this.status.E_BADARG("command","expected setSidebarPage");const n=this.clientObjects.get(e.id);if(!(n&&n instanceof R))return this.status.E_NOTFOUND(e.id);const s=D.expandResourcePath(this.getExtensionOrigin(t),e.page);if(void 0===s)return this.status.E_BADARG("page","Resources paths cannot point to non-extension resources");n.setPage(s)}onOpenResource(e){if("openResource"!==e.command)return this.status.E_BADARG("command","expected openResource");const t=h.Workspace.WorkspaceImpl.instance().uiSourceCodeForURL(e.url);if(t)return s.Revealer.reveal(t.uiLocation(e.lineNumber,e.columnNumber)),this.status.OK();const n=u.ResourceUtils.resourceForURL(e.url);if(n)return s.Revealer.reveal(n),this.status.OK();const i=a.NetworkLog.NetworkLog.instance().requestForURL(e.url);return i?(s.Revealer.reveal(i),this.status.OK()):this.status.E_NOTFOUND(e.url)}onSetOpenResourceHandler(e,t){if("setOpenResourceHandler"!==e.command)return this.status.E_BADARG("command","expected setOpenResourceHandler");const n=this.registeredExtensions.get(this.getExtensionOrigin(t));if(!n)throw new Error("Received a message from an unregistered extension");const{name:s}=n;e.handlerPresent?c.Linkifier.Linkifier.registerLinkHandler(s,this.handleOpenURL.bind(this,t)):c.Linkifier.Linkifier.unregisterLinkHandler(s)}onSetThemeChangeHandler(e,t){if("setThemeChangeHandler"!==e.command)return this.status.E_BADARG("command","expected setThemeChangeHandler");const n=this.getExtensionOrigin(t);if(!this.registeredExtensions.get(n))throw new Error("Received a message from an unregistered extension");e.handlerPresent?this.themeChangeHandlers.set(n,t):this.themeChangeHandlers.delete(n)}handleOpenURL(e,t,n){e.postMessage({command:"open-resource",resource:this.makeResource(t),lineNumber:n+1})}onReload(e){if("Reload"!==e.command)return this.status.E_BADARG("command","expected Reload");const n=e.options||{};let s;return t.NetworkManager.MultitargetNetworkManager.instance().setUserAgentOverride("string"==typeof n.userAgent?n.userAgent:"",null),n.injectedScript&&(s="(function(){"+n.injectedScript+"})()"),t.ResourceTreeModel.ResourceTreeModel.reloadAllPages(Boolean(n.ignoreCache),s),this.status.OK()}onEvaluateOnInspectedPage(e,t){if("evaluateOnInspectedPage"!==e.command)return this.status.E_BADARG("command","expected evaluateOnInspectedPage");const{requestId:n,expression:s,evaluateOptions:i}=e;return this.evaluate(s,!0,!0,i,this.getExtensionOrigin(t),function(e,s,i){let r;r=e||!s?this.status.E_PROTOCOLERROR(e?.toString()):i?{isException:!0,value:s.description}:{value:s.value},this.dispatchCallback(n,t,r)}.bind(this))}async onGetHAR(e){if("getHAR"!==e.command)return this.status.E_BADARG("command","expected getHAR");const t=a.NetworkLog.NetworkLog.instance().requests(),n=await l.Log.Log.build(t);for(let e=0;e<n.entries.length;++e)n.entries[e]._requestId=this.requestId(t[e]);return n}makeResource(e){return{url:e.contentURL(),type:e.contentType().name()}}onGetPageResources(){const e=new Map;function n(t){return e.has(t.contentURL())||e.set(t.contentURL(),this.makeResource(t)),!1}let s=h.Workspace.WorkspaceImpl.instance().uiSourceCodesForProjectType(h.Workspace.projectTypes.Network);s=s.concat(h.Workspace.WorkspaceImpl.instance().uiSourceCodesForProjectType(h.Workspace.projectTypes.ContentScripts)),s.forEach(n.bind(this));for(const e of t.TargetManager.TargetManager.instance().models(t.ResourceTreeModel.ResourceTreeModel))e.forAllResources(n.bind(this));return[...e.values()]}async getResourceContent(e,t,n){const s=e.contentURL(),i=H.get(n);if(!(i&&this.registeredExtensions.get(i))?.isAllowedOnTarget(s))return void this.dispatchCallback(t.requestId,n,this.status.E_FAILED("Permission denied"));const{content:r,isEncoded:o}=await e.requestContent();this.dispatchCallback(t.requestId,n,{encoding:o?"base64":"",content:r})}onGetRequestContent(e,t){if("getRequestContent"!==e.command)return this.status.E_BADARG("command","expected getRequestContent");const n=this.requestById(e.id);if(!n)return this.status.E_NOTFOUND(e.id);this.getResourceContent(n,e,t)}onGetResourceContent(e,t){if("getResourceContent"!==e.command)return this.status.E_BADARG("command","expected getResourceContent");const n=e.url,s=h.Workspace.WorkspaceImpl.instance().uiSourceCodeForURL(n)||u.ResourceUtils.resourceForURL(n);if(!s)return this.status.E_NOTFOUND(n);this.getResourceContent(s,e,t)}onSetResourceContent(e,n){if("setResourceContent"!==e.command)return this.status.E_BADARG("command","expected setResourceContent");const{url:s,requestId:i,content:r,commit:o}=e;const a=H.get(n);if(!(a&&this.registeredExtensions.get(a))?.isAllowedOnTarget(s))return this.status.E_FAILED("Permission denied");const c=h.Workspace.WorkspaceImpl.instance().uiSourceCodeForURL(s);if(!c||!c.contentType().isDocumentOrScriptOrStyleSheet()){return t.ResourceTreeModel.ResourceTreeModel.resourceForURL(s)?this.status.E_NOTSUPPORTED("Resource is not editable"):this.status.E_NOTFOUND(s)}c.setWorkingCopy(r),o&&c.commitWorkingCopy(),function(e){const t=e?this.status.E_FAILED(e):this.status.OK();this.dispatchCallback(i,n,t)}.call(this,null)}requestId(e){const t=this.requestIds.get(e);if(void 0===t){const t=++this.lastRequestId;return this.requestIds.set(e,t),this.requests.set(t,e),t}return t}requestById(e){return this.requests.get(e)}onForwardKeyboardEvent(t){if("_forwardKeyboardEvent"!==t.command)return this.status.E_BADARG("command","expected _forwardKeyboardEvent");t.entries.forEach((function(t){const n=new window.KeyboardEvent(t.eventType,{key:t.key,code:t.code,keyCode:t.keyCode,location:t.location,ctrlKey:t.ctrlKey,altKey:t.altKey,shiftKey:t.shiftKey,metaKey:t.metaKey});n.__keyCode=function(t){let n=t.keyCode;n||t.key===e.KeyboardUtilities.ESCAPE_KEY&&(n=27);return n||0}(t),document.dispatchEvent(n)}))}dispatchCallback(e,t,n){e&&t.postMessage({command:"callback",requestId:e,result:n})}initExtensions(){this.registerAutosubscriptionHandler("resource-added",h.Workspace.WorkspaceImpl.instance(),h.Workspace.Events.UISourceCodeAdded,this.notifyResourceAdded),this.registerAutosubscriptionTargetManagerHandler("network-request-finished",t.NetworkManager.NetworkManager,t.NetworkManager.Events.RequestFinished,this.notifyRequestFinished),this.registerSubscriptionHandler("panel-objectSelected-elements",function(){n.Context.Context.instance().addFlavorChangeListener(t.DOMModel.DOMNode,this.notifyElementsSelectionChanged,this)}.bind(this),function(){n.Context.Context.instance().removeFlavorChangeListener(t.DOMModel.DOMNode,this.notifyElementsSelectionChanged,this)}.bind(this)),this.registerResourceContentCommittedHandler(this.notifyUISourceCodeContentCommitted),t.TargetManager.TargetManager.instance().addEventListener(t.TargetManager.Events.InspectedURLChanged,this.inspectedURLChanged,this)}notifyResourceAdded(e){const t=e.data;this.postNotification("resource-added",this.makeResource(t))}notifyUISourceCodeContentCommitted(e){const{uiSourceCode:t,content:n}=e.data;this.postNotification("resource-content-committed",this.makeResource(t),n)}async notifyRequestFinished(e){const t=e.data,n=await l.Log.Entry.build(t);this.postNotification("network-request-finished",this.requestId(t),n)}notifyElementsSelectionChanged(){this.postNotification("panel-objectSelected-elements")}sourceSelectionChanged(e,t){this.postNotification("panel-objectSelected-sources",{startLine:t.startLine,startColumn:t.startColumn,endLine:t.endLine,endColumn:t.endColumn,url:e})}setInspectedTabId(e){const t=this.inspectedTabId;this.inspectedTabId=e.data,null===t&&this.initializeExtensions()}addExtensionFrame({startPage:e,name:t}){const n=document.createElement("iframe");n.src=e,n.dataset.devtoolsExtension=t,n.style.display="none",document.body.appendChild(n)}addExtension(e){const s=e.startPage,r=t.TargetManager.TargetManager.instance().primaryPageTarget()?.inspectedURL()??"";if(""===r)return void this.#n.push(e);if(D.canInspectURL(r)||this.disableExtensions(),!this.extensionsEnabled)return;const o=M.create(e.hostsPolicy);if(o){try{const t=new URL(s).origin,a=e.name||`Extension ${t}`,c=new j(a,o,Boolean(e.allowFileAccess));if(!c.isAllowedOnTarget(r))return;if(!this.registeredExtensions.get(t)){const s=self.buildExtensionAPIInjectedScript(e,this.inspectedTabId,d.ThemeSupport.instance().themeName(),n.ShortcutRegistry.ShortcutRegistry.instance().globalShortcutKeys(),D.instance().extensionAPITestHook);i.InspectorFrontendHost.InspectorFrontendHostInstance.setInjectedScriptForOrigin(t,s),this.registeredExtensions.set(t,c)}this.addExtensionFrame(e)}catch(e){return console.error("Failed to initialize extension "+s+":"+e),!1}return!0}}registerExtension(e,t){this.registeredExtensions.has(e)?(H.set(t,e),t.addEventListener("message",this.onmessage.bind(this),!1),t.start()):e!==window.location.origin&&console.error("Ignoring unauthorized client request from "+e)}onWindowMessage=e=>{"registerExtension"===e.data&&this.registerExtension(e.origin,e.ports[0])};extensionEnabled(e){if(!this.extensionsEnabled)return!1;const t=H.get(e);if(!t)return!1;const n=this.registeredExtensions.get(t);return!!n&&n.isAllowedOnTarget()}async onmessage(e){const t=e.data;let n;const s=e.currentTarget,i=this.handlers.get(t.command);n=i?this.extensionEnabled(s)?await i(t,e.target):this.status.E_FAILED("Permission denied"):this.status.E_NOTSUPPORTED(t.command),n&&t.requestId&&this.dispatchCallback(t.requestId,e.target,n)}registerHandler(e,t){console.assert(Boolean(e)),this.handlers.set(e,t)}registerSubscriptionHandler(e,t,n){this.subscriptionStartHandlers.set(e,t),this.subscriptionStopHandlers.set(e,n)}registerAutosubscriptionHandler(e,t,n,s){this.registerSubscriptionHandler(e,(()=>t.addEventListener(n,s,this)),(()=>t.removeEventListener(n,s,this)))}registerAutosubscriptionTargetManagerHandler(e,n,s,i){this.registerSubscriptionHandler(e,(()=>t.TargetManager.TargetManager.instance().addModelListener(n,s,i,this)),(()=>t.TargetManager.TargetManager.instance().removeModelListener(n,s,i,this)))}registerResourceContentCommittedHandler(e){this.registerSubscriptionHandler("resource-content-committed",function(){h.Workspace.WorkspaceImpl.instance().addEventListener(h.Workspace.Events.WorkingCopyCommittedByUser,e,this),h.Workspace.WorkspaceImpl.instance().setHasResourceContentTrackingExtensions(!0)}.bind(this),function(){h.Workspace.WorkspaceImpl.instance().setHasResourceContentTrackingExtensions(!1),h.Workspace.WorkspaceImpl.instance().removeEventListener(h.Workspace.Events.WorkingCopyCommittedByUser,e,this)}.bind(this))}static expandResourcePath(e,t){const n=new URL(e).origin,i=new URL(s.ParsedURL.normalizePath(t),n);if(i.origin===n)return i.href}evaluate(e,n,s,i,r,o){let a,c;if((i=i||{}).frameURL)c=function(e){let n=null;return t.ResourceTreeModel.ResourceTreeModel.frames().some((function(t){return n=t.url===e?t:null,n})),n}(i.frameURL);else{const e=t.TargetManager.TargetManager.instance().primaryPageTarget(),n=e&&e.model(t.ResourceTreeModel.ResourceTreeModel);c=n&&n.mainFrame}if(!c)return i.frameURL?console.warn("evaluate: there is no frame with URL "+i.frameURL):console.warn("evaluate: the main frame is not yet available"),this.status.E_NOTFOUND(i.frameURL||"<top>");const d=this.registeredExtensions.get(r);if(!d?.isAllowedOnTarget(c.url))return this.status.E_FAILED("Permission denied");let u;i.useContentScriptContext?u=r:i.scriptExecutionContext&&(u=i.scriptExecutionContext);const l=c.resourceTreeModel().target().model(t.RuntimeModel.RuntimeModel),h=l?l.executionContexts():[];if(u){for(let e=0;e<h.length;++e){const t=h[e];t.frameId!==c.id||t.origin!==u||t.isDefault||(a=t)}if(!a)return console.warn("The JavaScript context "+u+" was not found in the frame "+c.url),this.status.E_NOTFOUND(u)}else{for(let e=0;e<h.length;++e){const t=h[e];t.frameId===c.id&&t.isDefault&&(a=t)}if(!a)return this.status.E_FAILED(c.url+" has no execution context")}if(!d?.isAllowedOnTarget(a.origin))return this.status.E_FAILED("Permission denied");a.evaluate({expression:e,objectGroup:"extension",includeCommandLineAPI:n,silent:!0,returnByValue:s,generatePreview:!1},!1,!1).then((function(e){if("error"in e)return void o(e.error,null,!1);o(null,e.object||null,Boolean(e.exceptionDetails))}))}static canInspectURL(e){let t;try{t=new URL(e)}catch(e){return!1}return!!q.includes(t.origin)||"chrome:"!==t.protocol&&"devtools:"!==t.protocol&&"chrome-untrusted:"!==t.protocol&&((!t.protocol.startsWith("http")||"chrome.google.com"!==t.hostname||!t.pathname.startsWith("/webstore"))&&((!t.protocol.startsWith("http")||"chromewebstore.google.com"!==t.hostname)&&!(window.DevToolsAPI&&window.DevToolsAPI.getOriginsForbiddenForExtensions&&window.DevToolsAPI.getOriginsForbiddenForExtensions()||[]).includes(t.origin)))}disableExtensions(){this.extensionsEnabled=!1}}var N;!function(e){e.SidebarPaneAdded="SidebarPaneAdded",e.TraceProviderAdded="TraceProviderAdded"}(N||(N={}));class W extends n.View.SimpleView{name;panel;constructor(e,t,n){super(t),this.name=e,this.panel=n}viewId(){return this.name}widget(){return Promise.resolve(this.panel)}}class B{OK;E_EXISTS;E_BADARG;E_BADARGTYPE;E_NOTFOUND;E_NOTSUPPORTED;E_PROTOCOLERROR;E_FAILED;constructor(){function t(t,n,...s){const i={code:t,description:n,details:s};return"OK"!==t&&(i.isError=!0,console.error("Extension server error: "+e.StringUtilities.sprintf(n,...s))),i}this.OK=t.bind(null,"OK","OK"),this.E_EXISTS=t.bind(null,"E_EXISTS","Object already exists: %s"),this.E_BADARG=t.bind(null,"E_BADARG","Invalid argument %s: %s"),this.E_BADARGTYPE=t.bind(null,"E_BADARGTYPE","Invalid type for argument %s: got %s, expected %s"),this.E_NOTFOUND=t.bind(null,"E_NOTFOUND","Object not found: %s"),this.E_NOTSUPPORTED=t.bind(null,"E_NOTSUPPORTED","Object does not support requested operation: %s"),this.E_PROTOCOLERROR=t.bind(null,"E_PROTOCOLERROR","Inspector protocol error: %s"),this.E_FAILED=t.bind(null,"E_FAILED","Operation failed: %s")}}var U=Object.freeze({__proto__:null,HostsPolicy:M,ExtensionServer:D,get Events(){return N},ExtensionStatus:B});export{p as ExtensionAPI,E as ExtensionPanel,U as ExtensionServer,f as ExtensionView,v as HostUrlPattern,C as RecorderExtensionEndpoint,T as RecorderPluginManager};
